﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace AliyunOpenSearch4Net.Base
{
    class UnixTicksDateTimeConverter : DateTimeConverterBase
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            long ticks = 0;

            if (reader.TokenType == JsonToken.Integer)
            {
                ticks = (long)reader.Value;
                return ticks.FromUnixTicksToTime();
            }
            else if (reader.TokenType == JsonToken.String)
            {
                ticks = long.Parse(reader.Value.ToString());
                return ticks.FromUnixTicksToTime();
            }            

            throw new Exception("Wrong Token Type");
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            long val;

            if (value is DateTime)
            {
                val = (long)((DateTime)value).ToUnixTicks();
            }
            else
            {
                throw new Exception("Expected date object value.");
            }

            writer.WriteValue(val);
        }
    }
}
